package oop.ex3.usercommands;

import java.util.LinkedList;

import oop.ex3.filemanager.FileManager;
import oop.ex3.filemanager.UploadFile;
import oop.ex3.protocol.DontContainFile;
import oop.ex3.sharedclasses.IPaddress;

public class Remove extends UserMessage {

	public static final String COMMAND = "REMOVE";
	private String _fileName;
	
	/**
	 * Constructs a new Remove userCommand.
	 * sets fileName as the command's file-name.
	 * @param fileManager the FileManager using this UserMessage.
	 * @param fileName the fileName to be added.
	 */
	public Remove(FileManager fileManager, String fileName) {
		super(fileManager);
		this._fileName=fileName;
	}

	@Override
	public boolean run() {
		UploadFile toBeRemoved=this._fileManager.contains(_fileName);
		// null -> file is not found in the FileManager.
		if (toBeRemoved==null){
			System.out.println("It is impossible to delete an absent file");
			return FAILURE;
		}
		synchronized (toBeRemoved) {
			
			//TODO check if setNotUploadable is enough
			// Or the whole this needs to be synchronized
			toBeRemoved.setNotUploadable();
			this._fileManager.removeFromFileManager(_fileName);
			// by first removing from FileManager DB, FILENOTFOUND will be received
			// when asking for this file.
		}
		
		/*if (MyFileManager.finishUploading(this._fileManager ,toBeRemoved.getName())
				==SUCCESS){
			//Finished uploading the file;
		}*/
		//TODO ^ alternative,
		if (_fileManager.finishFileUpload(_fileName)){
			this._fileManager.removeFromDir(_fileName);
		}
		//Right now, toBeRemoved points to NULL!
		
		announceAllServers();
		System.out.println("Removing Done");
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	private void announceAllServers(){
		LinkedList<IPaddress> nameServers = _fileManager.getNameServerList();
		DontContainFile announcer = new DontContainFile();
		for (IPaddress nameServer : nameServers){
			announcer.runAsClient(_fileManager, nameServer, _fileName);
			//TODO check what happens after failure
			}
	}
}

